package com.order.controller.common;

import cn.hutool.core.io.FileUtil;
import com.order.config.QiNiuYunConfig;
import com.order.utils.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@RestController
@RequestMapping("/files")
@Api(tags = "文件上传下载接口")
public class FileController {

    @Value("${ip}")
    private String ip;

    @Value("${server.port}")
    private String port;

    @Autowired
    QiNiuYunConfig qiNiuYunConfig;

    private static final String ROOT_PATH = System.getProperty("user.dir") + "/files";

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取到原始的文件名   aaa.png   aaa.png
        String flag = UUID.randomUUID().toString();
        String fileName = flag + "." + originalFilename.split("\\.")[1];  // aaa.png -> flag.png
        String url = qiNiuYunConfig.uploadImgToQiNiu(file.getInputStream(), fileName);  // 上传到七牛云
        return Result.success(url);
    }

    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        File file = new File(ROOT_PATH + "/" + fileName);  // 文件在存盘存储的对象
        ServletOutputStream os = response.getOutputStream();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/octet-stream");
        // os.write(FileUtil.readBytes(file));
        FileUtil.writeToStream(file, os);
        os.flush();
        os.close();
    }
}
